<?php

declare(strict_types=1);

namespace App\Controller\AdminApi;

use App\Constants\StrStatus;
use App\Constants\XZXResponseCode;
use App\Exception\XZXValidationException;
use App\Middleware\AdminApi\AdminJWTAuthMiddleware;
use App\Middleware\AdminApi\NodeAccessMiddleware;
use App\Model\Enum\EventOrderTypeEnum;
use App\Model\Enum\OrderHandleStatusEnum;
use App\Service\EventOrderReviewService;
use App\Service\EventOrderService;
use App\Service\SysExportLogService;
use App\Utils\ArrayUtils;
use App\Utils\CustomUtils;
use App\Utils\DateUtils;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperf\Validation\Rule;

/**
 * Class EventOrderController
 *
 * @package App\Controller
 * @Controller(prefix="/admin/api/eventOrder")
 */
class EventOrderController extends AdminBaseController {
    /**
     * @Inject()
     * @var ValidatorFactoryInterface
     */
    protected $validationFactory;

    /**
     * @Inject()
     * @var SysExportLogService
     */
    protected $SysExportLogService;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    /**
     * @Inject()
     * @var EventOrderService
     */
    protected $EventOrderService;

    /**
     * @Inject()
     * @var EventOrderReviewService
     */
    protected $EventOrderReviewService;

    public function __construct (LoggerFactory $loggerFactory) {
        // 第一个参数对应日志的 name, 第二个参数对应 config/autoload/logger.php 内的 key
        $this->logger = $loggerFactory->get('log', 'default');
    }

    /**
     * 审核步骤
     * @PostMapping(path = "handleStatusOption")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function handleStatusOption (RequestInterface $request) {
        $data = (new OrderHandleStatusEnum())->getOptions();
        return CustomUtils::xeServiceReturnData(XZXResponseCode::SUCCESS_CODE, XZXResponseCode::getMessage(XZXResponseCode::SUCCESS_CODE), $data);
    }

    /**
     * 账号类型
     * @PostMapping(path = "accountOption")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function accountOption (RequestInterface $request) {
        $data = [
            1 => "可用账户",
            4 => "冻结账户",
        ];
        $data = ArrayUtils::ArrToOptions($data);
        return CustomUtils::xeServiceReturnData(XZXResponseCode::SUCCESS_CODE, XZXResponseCode::getMessage(XZXResponseCode::SUCCESS_CODE), $data);
    }

    /**
     * 类型
     * @PostMapping(path = "typeOption")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function typeOption (RequestInterface $request) {
        $data = (new EventOrderTypeEnum())->getOptions();
        return CustomUtils::xeServiceReturnData(XZXResponseCode::SUCCESS_CODE, XZXResponseCode::getMessage(XZXResponseCode::SUCCESS_CODE), $data);
    }

    /**
     * 查看
     * @PostMapping(path = "get")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function get (RequestInterface $request) {
        $validator = $this->validationFactory->make($request->all(), [
            'id' => 'required',
        ]);

        if ($validator->fails()) {
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param                = $request->all();
        $ext                  = $this->request->getAttribute("ext");
        $param['isSuperRole'] = $ext['isSuperRole'];
        if (!$param['isSuperRole']) {
            $param['mchIdList'] = $ext['mchIdList'];
        }
        $param['source'] = 2;
        return $this->EventOrderService->get($param);
    }

    /**
     * 添加
     * @PostMapping(path = "add")
     * @Middlewares({
     *     @Middleware(AdminJWTAuthMiddleware::class),
     *     @Middleware(NodeAccessMiddleware::class)
     * })
     */
    public function add (RequestInterface $request) {

        $validator = $this->validationFactory->make($request->all(), [
            'type'         => [
                'required',
                Rule:: in([8001, 8002, 8003, 8004]),
            ],
            'mchId'        => 'required|uuid',
            'mchNo'        => 'required',
            'amount'       => 'required|integer|min:0',
            'createRemark' => 'required',
        ]);

        if ($validator->fails()) {
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param                = $request->all();
        $ext                  = $this->request->getAttribute("ext");
        $param['isSuperRole'] = $ext['isSuperRole'];
        if (!$param['isSuperRole']) {
            $param['mchIdList'] = $ext['mchIdList'];
            if (!empty($param['mchIdList']) && !in_array($param['mchId'], $param['mchIdList'])) {
                throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::NO_PERMISSION_TO_OPERATE));
            }
        }
        $param['source']   = 2;
        $param['createBy'] = $ext['createBy'];
        return $this->EventOrderService->add($param);
    }

    /**
     * 查询
     * @PostMapping(path = "list")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function list (RequestInterface $request) {

        $validator = $this->validationFactory->make($request->all(), [
            'page'  => 'required|integer|min:1',
            'limit' => 'required|integer|min:1',
        ]);

        if ($validator->fails()) {
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        if (isset($param['search'])) {
            $search = $param['search'];
            CustomUtils::xzxAddSearch($param, $search, 'mchNo');
            CustomUtils::xzxAddSearch($param, $search, 'accountType');
            CustomUtils::xzxAddSearch($param, $search, 'type');
            CustomUtils::xzxAddSearch($param, $search, 'handleStatus');
            CustomUtils::xzxAddSearch($param, $search, 'createTimeRange');
            if (isset($param["createTimeRange"])) {
                try {
                    $param['createTimeRange'][0] = DateUtils::dateToTimeStamp($param['createTimeRange'][0]);
                    $param['createTimeRange'][1] = DateUtils::dateToTimeStamp($param['createTimeRange'][1]);
                } catch (\Throwable $th) {
                    unset($param['createTimeRange']);
                }
            }
        }

        $ext                  = $this->request->getAttribute("ext");
        $param['isSuperRole'] = $ext['isSuperRole'];
        if (!$param['isSuperRole']) {
            $param['mchIdList'] = $ext['mchIdList'];
        }
        $param['source'] = 2;
        return $this->EventOrderService->list($param);
    }

    /**
     * 导出
     * @PostMapping(path = "exportExcel")
     * @Middleware(AdminJWTAuthMiddleware::class)
     *
     * @param RequestInterface $request
     *
     * @return array|mixed
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     * @throws \Throwable
     * @throws \TypeError
     */
    public function exportExcel (RequestInterface $request) {

        $type = 3;

        // 新增导出记录
        $ext    = $this->request->getAttribute("ext");
        $result = $this->SysExportLogService->add(['type' => $type, 'createBy' => $ext['createBy']]);

        $param = $request->all();
        // 直接把页数拖到很大
        $param['source'] = 2;
        $param['page']   = $request->post('page', 1);
        $param['limit']  = 10000000;

        if (isset($param['search'])) {
            $search = $param['search'];
            CustomUtils::xzxAddSearch($param, $search, 'mchNo');
            CustomUtils::xzxAddSearch($param, $search, 'accountType');
            CustomUtils::xzxAddSearch($param, $search, 'type');
            CustomUtils::xzxAddSearch($param, $search, 'handleStatus');
            CustomUtils::xzxAddSearch($param, $search, 'createTimeRange');
            if(isset($param["createTimeRange"]))
            {
                try {
                    $param['createTimeRange'][0] = DateUtils::dateToTimeStamp($param['createTimeRange'][0]);
                    $param['createTimeRange'][1] = DateUtils::dateToTimeStamp($param['createTimeRange'][1]);
                } catch (\Throwable $th) {
                    unset($param['createTimeRange']);
                }
            }
        }

        $logId    = $result['data'];
        $fileName = 'eventOrder-'.date('YmdHis').rand(1000, 9999);
        $xlsCell  = [
            ['filed' => 'mchNo', 'name' => '商户号'],
            ['filed' => 'eventOrderNo', 'name' => '单号'],
            ['filed' => 'currency', 'name' => '币种'],
            ['filed' => 'strAccountType', 'name' => '操作账号类型'],
            ['filed' => 'strType', 'name' => '操作类型'],
            ['filed' => 'floatAmount', 'name' => '操作金额'],
            ['filed' => 'strHandleStatus', 'name' => '步骤'],
            ['filed' => 'createBy', 'name' => '创建人'],
            ['filed' => 'createRemark', 'name' => '创建备注'],
            ['filed' => 'createTime', 'name' => '创建时间'],
            ['filed' => 'strReviewStatus', 'name' => '初审状态'],
            ['filed' => 'reviewRemark', 'name' => '初审备注'],
            ['filed' => 'reviewBy', 'name' => '初审人'],
            ['filed' => 'reviewTime', 'name' => '初审时间'],
            ['filed' => 'strReReviewStatus', 'name' => '复审状态'],
            ['filed' => 'reReviewRemark', 'name' => '复审备注'],
            ['filed' => 'reReviewBy', 'name' => '复审人'],
            ['filed' => 'reReviewTime', 'name' => '复审时间'],
        ];

        $this->SysExportLogService->addToTask([
            'logId'    => $logId,
            'fileName' => $fileName,
            'type'     => $type,
            'param'    => $param,
            'xlsCell'  => $xlsCell,
        ]);

        return $result;
    }

    /**
     * 初审
     * @PostMapping(path = "actionCheck")
     * @Middlewares({
     *     @Middleware(AdminJWTAuthMiddleware::class),
     *     @Middleware(NodeAccessMiddleware::class)
     * })
     * @throws \Throwable
     */
    public function actionCheck (RequestInterface $request) {

        $validator = $this->validationFactory->make($request->all(), [
            'id'        => 'required',
            'isConfirm' => 'required',
        ]);

        if ($validator->fails()) {
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $ext = $this->request->getAttribute("ext");

        $param              = [
            'id'          => $request->post('id'),
            'isConfirm'   => !!$request->post('isConfirm'),
            'remark'      => $request->post('remark', ''),
            'reviewLevel' => 1,
        ];
        $param['createBy'] = $ext['createBy'];

        $param['source']      = 2;
        $param['isSuperRole'] = $ext['isSuperRole'];
        if (!$param['isSuperRole']) {
            $param['mchIdList'] = $ext['mchIdList'];
        }

        return $this->EventOrderReviewService->handleReview($param);
    }

    /**
     * 初审
     * @PostMapping(path = "actionRecheck")
     * @Middlewares({
     *     @Middleware(AdminJWTAuthMiddleware::class),
     *     @Middleware(NodeAccessMiddleware::class)
     * })
     * @throws \Throwable
     */
    public function actionRecheck (RequestInterface $request) {

        $validator = $this->validationFactory->make($request->all(), [
            'id'        => 'required',
            'isConfirm' => 'required',
        ]);

        if ($validator->fails()) {
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $ext = $this->request->getAttribute("ext");

        $param              = [
            'id'          => $request->post('id'),
            'isConfirm'   => !!$request->post('isConfirm'),
            'remark'      => $request->post('remark', ''),
            'reviewLevel' => 2,
        ];
        $param['createBy'] = $ext['createBy'];

        $param['source']      = 2;
        $param['isSuperRole'] = $ext['isSuperRole'];
        if (!$param['isSuperRole']) {
            $param['mchIdList'] = $ext['mchIdList'];
        }

        return $this->EventOrderReviewService->handleReview($param);
    }


}
